<template>
  <view class="page page-login">
    <!-- 头部 -->
    <view class="login-header">
      <image src="/static/images/logo.png" class="login-logo"></image>
      <fui-text class="login-title" text="供应链数字化运营平台" :size="38" fontWeight="bold"></fui-text>
      <fui-text class="login-title" text="供应链管理" :size="38" fontWeight="bold"></fui-text>
    </view>

    <!-- 手机号登录 -->
    <fui-form v-if="loginMethod === 'phone'" ref="phoneFormRef" :model="phoneForm" class="login-content" labelWeight="bold">
      <fui-form-item label="手机号" prop="phone" marginBottom="52" :padding="[0]" :bottomBorder="false">
        <template v-slot:vertical>
          <fui-input v-model="phoneForm.phone" bottomLeft="0" :padding="['38rpx', 0, '30rpx']" size="24" placeholder="请输入手机号"></fui-input>
        </template>
      </fui-form-item>
      <fui-form-item label="验证码" prop="code" marginBottom="52" :padding="[0]" :bottomBorder="false">
        <template v-slot:vertical>
          <fui-input v-model="phoneForm.code" bottomLeft="0" :padding="['38rpx', 0, '30rpx']" size="24" placeholder="请输入验证码">
            <fui-countdown-verify ref="sendCodeRef" width="auto" borderColor="#fff" color="var(--fui-color-link)" @send="onShowCaptcha"></fui-countdown-verify>
          </fui-input>
        </template>
      </fui-form-item>
      <view>
        <fui-button text="登 录" height="88rpx" radius="44rpx" :loading="isLoading" @click="handleLoginByPhone"></fui-button>
      </view>
      <view class="login-link" v-if="showRegister">
        <fui-text @click="tab.navigateTo(registerLink)">
          <fui-text text="供应链注册" size="24" color="var(--fui-color-link)"></fui-text>
          <fui-icon name="right" size="32" color="var(--fui-color-link)"></fui-icon>
        </fui-text>
      </view>
    </fui-form>

    <!-- 密码登录 -->
    <fui-form v-if="loginMethod === 'password'" ref="passwordFormRef" :model="passwordForm" class="login-content" labelWeight="bold">
      <fui-form-item label="用户名" prop="username" marginBottom="52" :padding="[0]" :bottomBorder="false">
        <template v-slot:vertical>
          <fui-input v-model="passwordForm.username" bottomLeft="0" :padding="['38rpx', 0, '30rpx']" size="24" placeholder="请输入用户名"></fui-input>
        </template>
      </fui-form-item>
      <fui-form-item label="密码" prop="password" marginBottom="52" :padding="[0]" :bottomBorder="false">
        <template v-slot:vertical>
          <fui-input v-model="passwordForm.password" bottomLeft="0" :padding="['38rpx', 0, '30rpx']" size="24" placeholder="请输入密码" :password="true">
            <fui-text text="忘记密码" size="24" color="var(--fui-color-link)" @click="tab.navigateTo(passwordLink)"></fui-text>
          </fui-input>
        </template>
      </fui-form-item>
      <view>
        <fui-button text="登 录" height="88rpx" radius="44rpx" :loading="isLoading" @click="onShowCaptcha"></fui-button>
      </view>
      <view class="login-link" v-if="showRegister">
        <fui-text @click="tab.navigateTo(registerLink)">
          <fui-text text="供应链注册" size="24" color="var(--fui-color-link)"></fui-text>
          <fui-icon name="right" size="32" color="var(--fui-color-link)"></fui-icon>
        </fui-text>
      </view>
    </fui-form>

    <!-- 底部 -->
    <view class="login-footer">
      <!-- <view style="display: flex; width: 100%; margin-bottom: 20rpx;">
        <fui-button text="供应商" style="flex: 1;" height="88rpx" radius="44rpx" @click="passwordForm.username = '13099140481'; passwordForm.password = 'Aa123654'"></fui-button>
        <fui-button text="未认证供应商" style="flex: 1; margin-left: 20rpx;" height="88rpx" radius="44rpx" @click="passwordForm.username = '17711881915'; passwordForm.password = 'Aa123654'"></fui-button>
      </view> -->
      
      <Verify ref="captchaRef" mode="pop" captchaType="blockPuzzle" :imgSize="{ width: '330px', height: '155px' }" @success="onCaptchaSuccess" @close="onCaptchaClose"></Verify>
      <view v-if="loginMethod === 'password'" class="login-method" @click="loginMethod = 'phone'">
        <image src="/static/images/login-phone.png" class="login-method-image"></image>
        <fui-text text="手机号登录" size="24" color="var(--fui-color-link)"></fui-text>
      </view>
      <view v-if="loginMethod === 'phone'" class="login-method" @click="loginMethod = 'password'">
        <image src="/static/images/login-password.png" class="login-method-image"></image>
        <fui-text text="密码登录" size="24" color="var(--fui-color-link)"></fui-text>
      </view>
      <view class="login-agreement" :class="{'is-shake': isShake}">
        <fui-label>
          <fui-checkbox :scaleRatio="0.6" :checked="isPassedAgreement" @change="onCheckAgreement"></fui-checkbox>
          <fui-text text="我已阅读并同意" size="20" color="#999999"></fui-text>
        </fui-label>
        <fui-text text="服务协议" size="20" color="var(--fui-color-link)" @click="tab.navigateTo(serviceLink)"></fui-text>
        <fui-text text="和" size="20" color="#999999"></fui-text>
        <fui-text text="隐私政策" size="20" color="var(--fui-color-link)" @click="tab.navigateTo(privacyLink)"></fui-text>
      </view>
      <view class="login-copyright">
        <fui-text text="Copytight@2022-2025  版权所有" size="20" color="#C7C7C7"></fui-text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import { onShow } from "@dcloudio/uni-app"
import { useStore } from 'vuex'
import { getAccessToken } from '@/utils/auth'
import Verify from '@/components/verifition/Verify'

const tab = inject('$tab')
const modal = inject('$modal')
const store = useStore()

const passwordLink = '/pages/user/password' // 忘记密码地址
const registerLink = '/pages/agreement/index' // 注册地址
const serviceLink = `/pages/common/webview?title=服务协议&url=https://szxz.online/scm-ui/agreement/service.html` // 服务协议地址
const privacyLink = `/pages/common/webview?title=隐私政策&url=https://szxz.online/scm-ui/agreement/privacy.html` // 隐私政策地址

const loginMethod = ref('password')
const isLoading = ref(false)
modal.closeLoading()

// 用户协议
const isPassedAgreement = ref(false)
const isShake = ref(false)
const onCheckAgreement = ({ checked }) => {
  isPassedAgreement.value = checked
}
const onShakeAgreement = () => {
  modal.msgError('请先勾选用户协议！')
  isShake.value = true
  setTimeout(() => {
    isShake.value = false
  }, 800)
}

// 手机号登录
const sendCodeRef = ref(null)
const phoneFormRef = ref(null)
const phoneForm = reactive({
  phone: '',
  code: ''
})
const msgCodeRules = [
  {
    name: 'phone',
    rule: ['required', 'isMobile'],
    msg: ['请输入手机号', '请输入正确的手机号']
  }
]
const phoneRules = [
  {
    name: 'phone',
    rule: ['required', 'isMobile'],
    msg: ['请输入手机号', '请输入正确的手机号']
  },
  {
    name: 'code',
    rule: ['required', 'minLength:4', 'maxLength:6'],
    msg: ['请输入验证码', '手机验证码长度为4-6位，请重新输入', '手机验证码长度为4-6位，请重新输入']
  }
]

const handleLoginByPhone = async () => {
  const validRes = await phoneFormRef.value.validator(phoneForm, phoneRules)
  if (validRes.isPassed) {
    if (!isPassedAgreement.value) {
      onShakeAgreement()
      return
    }
    isLoading.value = true
    store.dispatch('LoginByPhone', phoneForm).then(() => {
      isLoading.value = false
      loginSuccess()
    }).catch(err => {
      isLoading.value = false
      modal.msgError(err.msg)
    })
  }
}

// 密码登录
const passwordFormRef = ref(null)
const passwordForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
  tenantName: '供应链',
  captchaVerification: ''
})
const passwordRules = [
  {
    name: 'username',
    rule: ['required'],
    msg: ['请输入用户名']
  }, {
    name: 'password',
    rule: ['required'],
    msg: ['请输入密码']
  }
]
const handleLoginByPassword = () => {
  isLoading.value = true
  const formData = {
    ...passwordForm,
    username: passwordForm.username.trim()
  }
  store.dispatch('LoginByPassword', formData).then(() => {
    isLoading.value = false
    loginSuccess()
  }).catch(err => {
    isLoading.value = false
    modal.msgError(err.msg)
  })
}

// 滑动验证码
const captchaRef = ref(null)
const onShowCaptcha = async () => {
  if (loginMethod.value === 'password') {
    if (!isPassedAgreement.value) {
      onShakeAgreement()
      return
    }
    const validRes = await passwordFormRef.value.validator(passwordForm, passwordRules)
    if (validRes.isPassed) {
      captchaRef.value.show()
    }
  } else {
    const validRes = await phoneFormRef.value.validator(phoneForm, msgCodeRules)
    if (validRes.isPassed) {
      captchaRef.value.show()
    } else {
      sendCodeRef.value && sendCodeRef.value.reset()
    }
  }
}
const onCaptchaSuccess = (captchaParams) => {
  captchaRef.value.hide()
  if (loginMethod.value === 'password') {
    passwordForm.captchaVerification = captchaParams.captchaVerification
    handleLoginByPassword()
  } else {
    store.dispatch('SendMsgCode', phoneForm.phone).then(() => {
      sendCodeRef.value && sendCodeRef.value.success()
    }).catch(err => {
      sendCodeRef.value && sendCodeRef.value.reset()
      modal.msgError(err.msg)
    })
  }
}
const onCaptchaClose = () => {
  if (loginMethod.value === 'phone') {
    sendCodeRef.value && sendCodeRef.value.reset()
  }
}

const validatorLogin = (userInfo, showLoginMsg) => {
  const userArr = userInfo && userInfo.userType ? userInfo.userType.split(',') : []
  const userType = userArr.indexOf('2') > -1 ? '2' : '1'
  if (userType !== '1' && userType !== '2') {
    modal.msgError('无权限的用户！')
    return
  }
  if (userType === '1' && !userInfo.qyzt) {
    modal.msgError('供应链未启用！')
    return
  }

  if (showLoginMsg) modal.msg('登录成功！')
  tab.reLaunch('/pages/index')
}

// 登录成功后，处理函数
const loginSuccess = async (result) => {
  // 获取部门列表
  await store.dispatch('GetDeptList')

  // 设置用户信息
  const res = await store.dispatch('GetUserInfo')

  // 校验用户状态
  validatorLogin(res.data, true)
}

// 获取供应链注册信息
const showRegister = ref(false)
onShow(() => {
  // store.dispatch('GetRegisterInfo').then(res => {
  //   if (res && res.code === 0) {
  //     showRegister.value = !!res.data
  //   }
  // })
  
  if (getAccessToken() && store.getters.userInfo) {
    validatorLogin(store.getters.userInfo)
  }
})
</script>

<style lang="scss" scoped>
@import "@/static/scss/login.scss";
</style>
